package com.jswdwsx.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.util.CollectionUtils;
import org.apache.http.util.EntityUtils;


import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
public class HttpClientUtils {

    public static String doGet(String url) {
        return doGet(url, Collections.emptyList());
    }

    public static String doGet(String url, Map<String, String> param) {
        return doGet(url, param, Collections.emptyList());
    }

    public static String doGet(String url, List<Header> headers) {
        return doGet(url, null, headers);
    }

    public static String doGet(String url, Map<String, String> param, Map<String, String> headers) {
        return doGet(url, null, getHeaders(headers));
    }

    public static String doGet(String url, Map<String, String> param, List<Header> headerList) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            if (!CollectionUtils.isEmpty(headerList)) {
                headerList.forEach(httpGet::addHeader);
            }

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            log.error("httpClient doget exception", e);
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                log.error("httpClien doget close exception", e);
                e.printStackTrace();
            }
        }
        return resultString;
    }


    public static String doPost(String url) {
        return doPost(url, null, null);
    }

    public static String doPostJson(String url, String bodyJson) {
        return doPostJson(url, bodyJson, Collections.emptyList());
    }

    public static String doPostJson(String url, String bodyJson, Map<String, String> headerMap) {
        // 创建请求内容
        if (!CollectionUtils.isEmpty(headerMap)) {
            return doPostJson(url, bodyJson, getHeaders(headerMap));
        } else {
            return doPostJson(url, bodyJson);
        }
    }

    private static List<Header> getHeaders(Map<String, String> headerMap) {
        return headerMap.entrySet().stream().map(entry -> new BasicHeader(entry.getKey(), entry.getValue())).collect(Collectors.toList());
    }

    public static String doPostJson(String url, String bodyJson, List<Header> headers) {
        // 创建请求内容
        log.info("请求内容:{}", bodyJson);
        StringEntity entity = new StringEntity(bodyJson, ContentType.APPLICATION_JSON);
        return doPost(url, entity, headers);
    }


    public static String doPostFrom(String url, Map<String, String> param) {
        return doPostFrom(url, param, Collections.emptyList());
    }

    public static String doPostFrom(String url, Map<String, String> param, Map<String, String> headerMap) {
        if (!CollectionUtils.isEmpty(headerMap)) {
            return doPostFrom(url, param, getHeaders(headerMap));
        } else {
            return doPostFrom(url, param);
        }
    }

    public static String doPostFrom(String url, Map<String, String> param, List<Header> headerList) {

        // 创建参数列表
        if (!CollectionUtils.isEmpty(param)) {
            List<NameValuePair> paramList = new ArrayList<>();
            for (String key : param.keySet()) {
                paramList.add(new BasicNameValuePair(key, param.get(key)));
            }
            // 模拟表单
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Charset.forName("UTF-8"));
            return doPost(url, entity, headerList);
        } else {
            return doPost(url, null, headerList);
        }
    }

    public static String doPost(String url, AbstractHttpEntity entity, List<Header> headerList) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            if (!CollectionUtils.isEmpty(headerList)) {
                headerList.forEach(httpPost::addHeader);
            }

            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error("httpClient doPost exception", e);
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                log.error("httpClient doPost close exception", e);
            }
        }
        return resultString;
    }
}
